<!--mockFn 会影响element-plus的el-upload上传功能 不用时请关闭 -->
<template>
  <el-upload v-model:file-list="fileList" v-loading="uploading"  v-bind="initialProp()">
    <template v-if="item.type == 'uImg'">
      <img v-if="fileUrl != ''" :src="fileUrl" class="img_uploader_img" />
      <Icon v-else icon="Plus" class="img_uploader_icon"></Icon>
    </template>
    <Icon v-else-if="item.type == 'uImgs'" icon="Plus" class="img_uploader_icon"></Icon>
    <template v-else>
      <el-button size="default" type="primary" :loading="uploading">{{ item?.btnText || "上传" }}</el-button>
      <el-button style="width: 100px" v-if="item.type == 'uGetExcelData'" size="default" type="primary" :loading="uploading" @click.stop="emitDownTemplate">下载模板</el-button>
      <template v-if="item.type == 'uVideo'">
        <video v-for="item in fileList" :key="item" :src="item" style="height: 200px" controls x-webkit-airplay playsinline webkit-playsinline></video>
      </template>
    </template>
  </el-upload>
  <el-dialog v-model="open" v-if="item.type == 'uImgs'">
    <img style="width: 100%" :src="dialogImageUrl" alt="" />
  </el-dialog>
</template>

<script lang="ts" setup>
import * as XLSX from "xlsx";
import type { IUploadP } from "../index";
import type { UploadFile, UploadRawFile } from "element-plus";
import { appConfig } from "../../../appConfig/index";
import { utilGetCookie } from "@/assets/utils";

let props = withDefaults(defineProps<IUploadP>(), {});
const emit = defineEmits(["emitBeforeUpload", "emitGetFile", "emitDownTemplate",'emitHttpRequest']);
const ufileType: { [key in IUploadPType]: any } = {
  uGetExcelData: ".xlsx,.xls",
  uFile: ".xlsx,.xls",
  uVideo: ".mp4,.quicktime",
  uAudio: ".mp3,.m4a",
  uImg: ".jpg,.png,.jpeg,.tif,.tiff",
  uImgs: ".jpg,.png,.jpeg,.tif,.tiff"
};
const fileUrl = ref("");
const dialogImageUrl = ref("");
const open = ref(false);
const fileList = ref([]);
const uploading = ref(false);
function handleBefore(file: UploadRawFile) {
  emit("emitBeforeUpload", { file });
}
const successFn = (file: any) => {
  uploading.value = false;
  if (props.item.type == "uImg") {
    fileUrl.value = file.data;
    return emit("emitGetFile", { e: fileUrl.value[0] });
  }
  return emit("emitGetFile", { e: fileList.value });
};
// 查看大图
const handlePreview = (file: UploadFile) => {
  // if (!file.url) return ElMessage.error("缺少图片地址");
  dialogImageUrl.value = file.url as string;
  open.value = true;
};
const handleRemove = (file: UploadFile) => {
  if (file.status === "success") {
    emit("emitGetFile", { e: fileList.value });
  }
};
const commonUploadProps = {
  limit: props.item?.limit || 12,
  // fileList: fileList.value,
  "before-upload": handleBefore,
  "on-success": successFn
};
const uploadPropsList = {
  uImg: {
    class: "img_uploader",
    "show-file-list": false,
    "on-preview": handlePreview,
    "on-success": successFn
  },
  uImgs: {
    class: "img_uploader",
    limit: props.item?.limit || 12,
    "list-type": "picture-card",
    "on-preview": handlePreview,
    "on-success": successFn,
    "on-remove": handleRemove
  },
  uVideo: { ...commonUploadProps, "on-remove": handleRemove },
  uAudio: { ...commonUploadProps, "on-remove": handleRemove },
  uFile: { ...commonUploadProps, "on-remove": handleRemove },
  uGetExcelData: {
    limit: 1,
    "on-change": (e: any) => {
      if (e.status !== "ready") return;
      if (e.length <= 0) {
        ElMessage.warning("请选择文件");
      } else if (e.name.split(".")[1] !== "xlsx") {
        ElMessage.warning("上传格式不正确，请上传xlsx格式");
      } else {
        const file = e.raw;
        const reader = new FileReader();
        reader.readAsArrayBuffer(file);
        reader.onload = async (ev) => {
          const workbook = XLSX.read(ev.target!.result, { type: "binary", cellDates: true });
          const wsname = workbook.SheetNames[0];
          const getData = XLSX.utils.sheet_to_json(workbook.Sheets[wsname]);
          emit("emitGetFile", { e: getData });
        };
      }
    }
  },
  // "auto-upload": false
  // uUpLoad:{
  //   'http-request':true,
  //   "on-success": (file: any)=>{
  //     uploading.value = false;
  //   }
  // }
};

function initialProp() {
  let obj:any={}
  if(props.item.httpRequest){
    obj['http-request']=(file:any)=>{
      emit("emitHttpRequest", { e: file,fileUrl });
    }
  }
  return {
    action: props.item.httpRequest?'':appConfig[import.meta.env.MODE as IEnvOType].IMG_UPLOAD_URL,
    accept: props.item.uploadFileType || ufileType[props.item.type],
    headers: {
      Authorization: utilGetCookie("token")
    },
    ...uploadPropsList[props.item.type],...obj
  };
}
function emitDownTemplate() {
  emit("emitDownTemplate", { item: props.item });
}
const uploadExpose: IUploadEx = {
  fileList,
  fileUrl,
};

defineExpose({ ...uploadExpose });
</script>

<style lang="scss">
.img_uploader {
  .img_uploader_img {
    width: 140px;
  }
  .el-upload--text {
    width: 140px;
    height: 140px;
    border: 1px dashed #beb1b1;
    display: flex;
    align-items: center;
    border-radius: 6px;
    cursor: pointer;
    overflow: hidden;
    justify-content: center;
  }
  .img_uploader_icon {
    width: 30px;
    height: 30px;
  }
}
.video-uploader .el-upload--text {
  width: auto;
  height: auto;
}
</style>
